<template>
  <div class="panel-wrapper" :class="sceneStore.layerPanelVisible ? 'active' : ''">
    <div class="panel-inner">
      <div class="panel-handler" @click="togglePanelVisible">
        <SvgIcon icon-class="ic_close_gray" />
      </div>

      <div class="panel">
        <div class="panel-header">
          <span>图层</span>
        </div>

        <div class="panel-body">
          <div class="body-title">
            <span>图层</span>
            <SvgIcon class="import-icon" icon-class="ic_导入" @click="importLayers" />
            <SvgIcon class="folder-icon" icon-class="ic_文件夹" @click="createFolder" />
          </div>
          <LayerTree
            ref="layerTreeRef"
            :is-location="isLocation"
            @loaction="layerLocation"
            @selectLayer="selectLayer"
          ></LayerTree>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getModelReadyMap, getService, poiClickCallback, destroyOrbitControl } from '@/service';
import { useSceneStore } from '@/store/scene';
import { randomString } from '@/utils/index';
import { messageUtil } from '@jl/element-plus/utils';
import type Node from 'element-plus/es/components/tree/src/model/node';
import LayerTree from './layer-tree/layer-tree.vue';
import { initTridentEvent } from '@/service/layer';

defineOptions({
  name: 'Layer',
});

const sceneStore = useSceneStore();
const topHeight = ref(320);
const emit = defineEmits(['toggleVisible']);

const togglePanelVisible = () => {
  sceneStore.layerPanelVisible = !sceneStore.layerPanelVisible;
  emit('toggleVisible');
};

const layerTreeRef = ref<any>();

const isLocation = (data: any) => {
  return [
    'gltfmodel',
    'div',
    'entity',
    'marker',
    'drawlabel',
    'road',
    'building',
    'fake_particleSystem',
    'osgb',
    '_3dtiles',
    'tileset',
    'point',
    'polyline',
    'polygon',
    'bimModel',
    'image',
    'regionEffect',
  ].includes(data.type);
};

onMounted(async () => {
  const savedHeight = localStorage.getItem('LayerPanelTopHeight');
  if (savedHeight) {
    topHeight.value = +savedHeight;
  }
  await getService();
  window.addEventListener('keydown', quickOperation);
});

onBeforeUnmount(() => {
  const { cimInstance } = window;
  // 销毁当前三轴
  sceneStore.selLayer && destroyOrbitControl(sceneStore.selLayer);
  window.removeEventListener('keydown', quickOperation);
  // 取消特效编辑模式
  cimInstance.api.cancelEdit();
  // 取消div图层编辑模式
  sceneStore.divEditLayerName = '';
});

// 导入资源
const importLayers = () => {
  sceneStore.leftPanelVisible = true;
  sceneStore.leftPanelActive = 'import';
  sceneStore.sourceType = 'layerImport';
};

// 创建图层
const createFolder = () => {
  const treeRef = layerTreeRef.value?.$refs?.treeRef || {};
  const data = {
    type: 'folder',
    name: '新建文件夹',
    fe_id: randomString(), // fe_ 前端字段
    fe_checked: true,
    fe_indeterminate: false,
    fe_parentId: '', // 前端字段
    id: '',
  };
  data.id = data.fe_id;
  // 当前选中节点
  if (sceneStore.selectedLayerNode) {
    const currNode: Node = sceneStore.selectedLayerNode;
    const currentNodeData = sceneStore.selectedLayerNode.data;
    // 选中为 文件夹
    if (currentNodeData.type === 'folder') {
      if (!currentNodeData.children) {
        currentNodeData.children = [{ ...data, fe_parentId: currentNodeData.fe_id }];
      } else {
        currentNodeData.children.splice(0, 0, {
          ...data,
          fe_parentId: currentNodeData.fe_id,
        });
      }
      currNode.expanded = true;
    } else {
      // 图层资源
      const parentNode = currNode.parent;
      let index;
      if (parentNode.level === 0) {
        // 根节点增加
        index = sceneStore.layerTree.findIndex((v: any) => v.fe_id === currentNodeData.fe_id);
        sceneStore.layerTree.splice(index, 0, data);
      } else {
        index = parentNode.data.children.findIndex((v: any) => v.fe_id === currNode.data.fe_id);
        parentNode.data.children.splice(index, 0, { ...data, fe_parentId: parentNode.data.fe_id });
        parentNode.expanded = true;
      }
    }
  } else {
    sceneStore.layerTree.unshift(data);
  }
  const currentCheckedKeys = treeRef.getCheckedKeys(true);
  treeRef.setCheckedKeys([...currentCheckedKeys, data.fe_id], true);
};

function selectLayer(layer: API.Scene.ILayer, event: any) {
  const { cimInstance } = window;
  cimInstance.api.cancelEdit();
  sceneStore.divEditLayerName = '';
  if (!layer.effect) {
    layer.effect = {
      dataType: '2', // 1静态数据2动态数据
      request: {
        method: 'GET',
        url: '',
        ticket: '',
        data: '',
        refrush: 0,
        isRefrush: false,
      },
      fieldDef: [],
      dataMapping: {},
      requestData: [],
      list: [], // 判定器列表
    };
  }
  // 暂时屏蔽
  // if (
  //   ['entity', 'fake_particleSystem'].includes(layer.type) ||
  //   (layer.type === 'gltfmodel' && layer.json.createType)
  // ) {
  //   const readyMap = getModelReadyMap();
  //   if (!readyMap.get(layer.layerName)) {
  //     messageUtil.warning('模型还未加载完成，请稍后再试');
  //     return;
  //   }
  // }
  sceneStore.specialEffectVisible = false;
  // 销毁当前三轴
  sceneStore.selLayer && destroyOrbitControl(sceneStore.selLayer);
  sceneStore.selLayer = layer;
  initTridentEvent(layer);
  if (layer.type === 'div') {
    sceneStore.divEditLayerName = layer.layerName;
  }
  sceneStore.specialEffectVisible = true;
}

function layerLocation(layer: API.Scene.ILayer) {
  const { cimInstance } = window;
  if (['div'].includes(layer.type)) {
    const params = cimInstance.api.getCameraParameter();
    cimInstance.api.lookModel(
      layer.attr.position[0],
      layer.attr.position[1],
      layer.attr.position[2],
      params.heading,
      params.patch,
      100,
      0.7
    );
    return;
  }
  if (
    [
      'road',
      'regionEffect',
      'drawlabel',
      'building',
      'tileset',
      'point',
      'polyline',
      'polygon',
      'bimModel',
      'image',
    ].includes(layer.type) ||
    (layer.actualType && ['gltfmodeleffect'].includes(layer.actualType)) ||
    (layer.type === 'gltfmodel' && !layer.json.createType)
  ) {
    cimInstance.api.zoomToLayer(layer.layerName);
    return;
  }
  const readyMap = getModelReadyMap();
  if (!readyMap.get(layer.layerName)) {
    messageUtil.warning('模型还未加载完成，请稍后再试');
    return;
  }
  cimInstance.api.zoomToLayer(layer.layerName);
}

// 键盘快捷操作
function quickOperation(event?: any) {
  const keyCode = event.keyCode;
  if (!sceneStore.selLayer) return;
  // 判断焦点元素
  if (document.activeElement!.localName !== 'body') {
    return;
  }
  const { cimInstance } = window;
  if (keyCode === 81) {
    // 隐藏3轴
    const orbitControlMode = cimInstance.api.getOrbitControlMode();
    if (orbitControlMode !== 'NONE') {
      cimInstance.api.changeOrbitControlMode('');
    } else {
      cimInstance.api.changeOrbitControlMode('translation');
    }
    return;
  }
  if (keyCode === 69) {
    // 旋转
    cimInstance.api.changeOrbitControlMode('rotation');
    return;
  }
  if (keyCode === 87) {
    // 移动
    cimInstance.api.changeOrbitControlMode('translation');
    return;
  }
  if (keyCode === 82) {
    // 缩放
    cimInstance.api.changeOrbitControlMode('scale');
  }
}

watch(
  () => sceneStore.layerTree,
  (newval: API.Scene.ILayer[]) => {
    initSelectedLayerNode();
  },
  {
    deep: true,
  }
);

// 图层共计复制图层，默认图层节点
function initSelectedLayerNode() {
  if (sceneStore.selLayer?.type === 'gltfmodel') {
    if (sceneStore?.selectedLayerNode?.data?.layerName !== sceneStore.selLayer?.layerName) {
      const treeRef = layerTreeRef.value?.$refs?.treeRef || null;
      if (!treeRef) return;
      const node = treeRef.getNode((sceneStore.selLayer as any).fe_id);
      sceneStore.selectedLayerNode = node;
    }
  }
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>
